<template>
  <div v-loading="loading" class="spu-series">
    <div class="btn-list">
      <el-button
        v-if="(!isDisabled || isEditorDescription) && listDisplay.attribute && listDisplay.JD_channel && listDisplay.WMDJ_channel"
        round
        type="primary"
        size="mini"
        @click="submitSpuMark"
      >
        {{ upcChangeFlag ? '更新到渠道' : '提交' }}
      </el-button>
      <el-button v-if="!increased && isShowButton" round type="primary" size="mini" @click="submitSpuMark">
        {{ upcChangeFlag ? '更新到渠道' : '提交' }}
      </el-button>
      <el-button round size="mini" @click="goBlack">返回</el-button>
    </div>
    <el-tabs v-model="activeName" type="card" :before-leave="beforeLeave">
      <el-tab-pane v-if="increased" label="系列" name="series">
        <series
          ref="series"
          :increased="increased"
          :spu-data="spuData"
          :is-disabled="isDisabled"
          :list-display="listDisplay"
          @changeLoading="changeLoading"
          @refresh="refresh"
          @changeTag="changeTag"
        />
      </el-tab-pane>
      <el-tab-pane v-if="listDisplay.attribute && increased" label="销售属性排序" name="attribute">
        <sales-attributes
          ref="attribute"
          v-model="salesAttributesList"
          :increased="increased"
          :is-disabled="isDisabled"
          :list-display="listDisplay"
          @changeLoading="changeLoading"
          @refresh="refresh"
          @changeTag="changeTag"
        />
      </el-tab-pane>
      <el-tab-pane v-if="!increased" label="销售属性系列" name="series">
        <series-list
          ref="series"
          increased="increased"
          :spu-data="spuData"
          :is-disabled="isDisabled"
          :list-display="listDisplay"
          @changeLoading="changeLoading"
          @refresh="refresh"
          @changeTag="changeTag"
        />
        <!-- <series
          ref="series"
          :increased="increased"
          :spu-data="spuData"
          :is-disabled="isDisabled"
          :list-display="listDisplay"
          @changeLoading="changeLoading"
          @refresh="refresh"
          @changeTag="changeTag"
        /> -->
      </el-tab-pane>
      <el-tab-pane v-if="listDisplay.JD_channel" label="京东SPU" name="JD_channel">
        <JD-channel
          ref="JD_channel"
          :increased="increased"
          :is-disabled="isDisabled"
          :spu-data="spuData"
          :channel-info="JD_channelInfo"
          :is-editor-description="isEditorDescription"
          :get-sinking-attribute-fun="getSinkingAttributeFun"
          :sava-sinking-attribute-fun="savaSinkingAttributeFun"
          @saveSpuChannelInfo="saveSpuChannelInfo"
        />
      </el-tab-pane>
      <el-tab-pane v-if="listDisplay.WMDJ_channel" label="WMDJ SPU" name="WMDJ_channel">
        <WMDJChannel
          ref="WMDJ_channel"
          :is-disabled="isDisabled"
          :spu-data="spuData"
          :channel-info="WMDJ_channelInfo"
          @saveSpuChannelInfo="saveSpuChannelInfo"
        />
      </el-tab-pane>
    </el-tabs>
  </div>
</template>
<script>
/* eslint-disable no-unused-vars */
import series from '../components/series.vue'
import seriesList from '../components/series-list'
import salesAttributes from '../components/salesAttributes.vue'
import JDChannel from '../components/JD_channel.vue'
import WMDJChannel from '../components/WMDJ_channel.vue'
import {
  getVerificationInfo,
  saveSpuChannelInfo,
  saveSpuContent,
  setSpuChannelInfo,
  setSpuContent,
  getSkuAttrInfo,
  updateSkuAttr
} from '@/api/coi/onlineTaskAPI/spu.js'
import {
  getchgSpuDetailById,
  saveChgSpuChannelInfo,
  saveChgSpuContent,
  setChgSpuChannelInfo,
  setChgSpuContent,
  getChgSpuInfoBySpuCode,
  getChgSkuAttr,
  updateChgSkuAttr
} from '@/api/coi/onlineTaskAPI/spuEdit.js'
import { CreateObject, transTemplateData, transSavaData, subscriptValue } from '@/utils/processingData.js'
import eventBus from '@/utils/eventBus'

export default {
  name: 'SpuSeries',
  components: { series, salesAttributes, JDChannel, WMDJChannel, seriesList },
  data() {
    return {
      loading: false,
      activeName: 'series',
      spuId: this.$route.params.spuId,
      params: this.$route.params,
      query: this.$route.query,
      spuData: {
        skuInfoList: [],
        mainAttrName: '',
        secondaryAttrName: '',
        mainAliasList: [],
        secondAliasList: [],
        channelInfoList: []
      },
      salesAttributesList: [],
      JD_channelInfo: null,
      WMDJ_channelInfo: null,
      getInfoFun: getVerificationInfo, // 信息
      submitBtnFun: setSpuChannelInfo, // 提交
      saveSpuChannelInfoFun: saveSpuChannelInfo, // 保存
      getSinkingAttributeFun: getSkuAttrInfo,
      savaSinkingAttributeFun: updateSkuAttr,
      isShowButton: false
    }
  },
  computed: {
    upcChangeFlag() {
      return (
        this.params.from === 'SpuTeamDescription' ||
        (!this.increased && !this.spuData.chgChangeRemarkDTO) ||
        (!this.increased && this.spuData.chgChangeRemarkDTO && !this.spuData.chgChangeRemarkDTO.addFlag && !this.spuData.chgChangeRemarkDTO.deleteFlag)
      )
    },
    listDisplay() {
      return {
        series: true,
        attribute: Boolean(this.salesAttributesList.filter((_) => _.attrName && Array.isArray(_.aliasList) && _.aliasList.length).length),
        JD_channel: Boolean(this.JD_channelInfo),
        WMDJ_channel: Boolean(this.WMDJ_channelInfo)
      }
    },
    isDisabled() {
      const params = this.params
      console.log('params', params)
      if (params.from === 'OnlineBuildingTasks' && params.mainStatus === '201') return false
      else if (this.params.mainStatus === 'details') return true
      else if (params.from === 'GoodsLibrary' || this.params.from === 'ChannelInventory') return false
      // 从商品库
      else return true
    },
    isEditorDescription() {
      const params = this.params
      if (params.from === 'SpuTeamDescription' && params.mainStatus === '301') return true
      else return false
    },
    increased() {
      // newProducts 为新增
      return this.query.menuName === 'newProducts' // 是否新增
    }
  },
  watch: {
    spuData() {
      this.salesAttributesList = this.initSalesAttributesList()
    }
  },
  async created() {
    // console.log('route', this.$route)
    eventBus.$on('loadingChange', (status) => {
      this.loading = status
    })
    if (this.params.from === 'OnlineBuildingTasks' && this.query.menuName === 'newProducts') {
      // 采销新增
      this.getInfoFun = getVerificationInfo
      this.submitBtnFun = setSpuChannelInfo
      this.saveSpuChannelInfoFun = saveSpuChannelInfo
      this.getSinkingAttributeFun = getSkuAttrInfo
      this.savaSinkingAttributeFun = updateSkuAttr
    } else if (this.params.from === 'SpuTeamDescription' && this.query.menuName === 'newProducts') {
      // 文描团队新增
      this.getInfoFun = getVerificationInfo
      this.submitBtnFun = setSpuContent
      this.saveSpuChannelInfoFun = saveSpuContent
      this.getSinkingAttributeFun = getSkuAttrInfo
      this.savaSinkingAttributeFun = updateSkuAttr
    } else if (this.params.from === 'OnlineBuildingTasks' && this.query.menuName === 'safeguard') {
      // 采销维护
      this.getInfoFun = getchgSpuDetailById
      this.submitBtnFun = setChgSpuChannelInfo
      this.saveSpuChannelInfoFun = saveChgSpuChannelInfo
      this.getSinkingAttributeFun = getChgSkuAttr
      this.savaSinkingAttributeFun = updateChgSkuAttr
    } else if (this.params.from === 'GoodsLibrary' || this.params.from === 'ChannelInventory') {
      // 采销维护（商品库进入）
      if (this.params.mainStatus === 'details') this.getInfoFun = getChgSpuInfoBySpuCode
      else this.getInfoFun = getchgSpuDetailById
      this.submitBtnFun = setChgSpuChannelInfo
      this.saveSpuChannelInfoFun = saveChgSpuChannelInfo
      this.getSinkingAttributeFun = getChgSkuAttr
      this.savaSinkingAttributeFun = updateChgSkuAttr
    } else if (this.params.from === 'SpuTeamDescription' && this.query.menuName === 'safeguard') {
      // 文描团队维护
      this.getInfoFun = getchgSpuDetailById
      this.submitBtnFun = setChgSpuContent
      this.saveSpuChannelInfoFun = saveChgSpuContent
      this.getSinkingAttributeFun = getChgSkuAttr
      this.savaSinkingAttributeFun = updateChgSkuAttr
    }
    await this.requestData()
    const activeName = this.$route.query.activeName
    if (activeName && this.listDisplay[activeName]) this.activeName = activeName
  },
  methods: {
    beforeLeave() {
      if (this.$refs[this.activeName].isChange) {
        const p = new Promise((resolve, reject) => {
          this.$confirm('当前页面已做修改，是否保存？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
            // eslint-disable-next-line space-before-function-paren
            .then(async () => {
              await this.$refs[this.activeName].sava()
              resolve()
            })
            .catch(() => {
              this.requestData()
              resolve()
              // 你可以在这儿做些操作
              // reject(err)
            })
        })
        return p
      } else {
        return true
      }
    },
    changeTag(tagName) {
      if (!this.listDisplay[tagName]) return
      this.activeName = tagName
    },
    async refresh(tagName) {
      await this.requestData()
      this.changeTag(tagName)
    },
    changeLoading(status = false) {
      this.loading = status
    },
    initSalesAttributesList() {
      const arr = new Array(0)
      const { mainAttrName, mainAliasList, secondaryAttrName, secondAliasList } = this.spuData
      // if (mainAttrName && Array.isArray(mainAliasList) && mainAliasList.length) {
      arr.push(
        new CreateObject(
          { key: 'attrName', value: mainAttrName },
          { key: 'aliasList', value: mainAliasList },
          { key: 'attrNameKey', value: 'mainAttrName' },
          { key: 'aliasListKey', value: 'mainAliasList' }
        )
      )
      // }
      // if (secondaryAttrName && Array.isArray(secondAliasList) && secondAliasList.length) {
      arr.push(
        new CreateObject(
          { key: 'attrName', value: secondaryAttrName },
          { key: 'aliasList', value: secondAliasList },
          { key: 'attrNameKey', value: 'secondaryAttrName' },
          { key: 'aliasListKey', value: 'secondAliasList' }
        )
      )
      // }
      return arr
    },
    goBlack() {
      this.$router.push({
        name: this.$route.params.from,
        params: { tab: this.query.menuName, type: 'spu' }
      })
    },
    async requestData() {
      try {
        this.loading = true
        let key = 'spuId'
        if (this.params.mainStatus === 'details') key = 'spuCode'
        else if (this.increased) key = 'spuId'
        else key = 'chgSpuId'
        const data = {
          [key]: this.spuId
        }
        const { result } = await this.getInfoFun(data)
        if (!result) return
        this.modifyStatusChange()
        result.skuInfoList = Array.isArray(result.skuInfoList) ? result.skuInfoList : []
        if (Array.isArray(result.channelInfoList)) {
          if (this.findChannelIndex(result.channelInfoList, 6) !== -1) {
            const JD_channelInfo = result.channelInfoList[this.findChannelIndex(result.channelInfoList, 6)] // 京东渠道06
            if (JD_channelInfo.channelBrandId) JD_channelInfo.channelBrandId -= 0
            this.picTrans(JD_channelInfo)
            JD_channelInfo.spuChannelBaseAttrCopy = JSON.parse(JSON.stringify(JD_channelInfo.spuChannelBaseAttr))
            if (Array.isArray(JD_channelInfo.spuChannelBaseAttr)) {
              JD_channelInfo.spuChannelBaseAttr = JD_channelInfo.spuChannelBaseAttr.filter(
                (item) => subscriptValue(item.spuEditFlag, false, this.increased ? 1 : 2) === 1
              )
            }
            transTemplateData(JD_channelInfo.spuChannelBaseAttr)
            transTemplateData(JD_channelInfo.spuChannelCategoryAttrList, false, true, true)
            this.JD_channelInfo = JD_channelInfo
          }
          if (this.findChannelIndex(result.channelInfoList, 12) !== -1) {
            const WMDJ_channelInfo = result.channelInfoList[this.findChannelIndex(result.channelInfoList, 12)] // 沃尔玛到家渠道12
            this.WMDJ_channelInfo = WMDJ_channelInfo
          }
        } else {
          this.JD_channelInfo = null
          this.WMDJ_channelInfo = null
        }
        this.spuData = result
      } finally {
        this.loading = false
      }
    },
    findChannelIndex(item, v) {
      return item.findIndex((_) => _.channelId - 0 === v)
    },
    submitSpuMark() {
      if (this.increased) {
        if (!this.$refs.series.checkFormData()) {
          return this.$message({
            type: 'error',
            message: '系列信息不完整，请切换到系列页签填写完整信息后再提交！'
          })
        }
      }

      if (!this.$refs.JD_channel.checkFormData()) {
        return this.$message({
          type: 'error',
          message: '京东渠道信息不完整，请切换到京东SPU页签填写完整信息后再提交！'
        })
      }
      this.$confirm('提交SPU信息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(this.spuSubmitRequest)
        .catch(() => {})
    },
    async spuSubmitRequest() {
      try {
        this.loading = true
        const { code } = await this.submitBtnFun(this.transChanneInfo())
        if (code !== '0') return
        this.$message({
          type: 'success',
          message: '提交成功'
        })
        eventBus.$emit('closeTag', this.$route)
      } finally {
        this.loading = false
      }
    },
    picTrans(v) {
      if (v && Array.isArray(v.spuResourceList)) {
        v.mainGraph = v.spuResourceList.filter((_) => _.resourceType - 0 === 1)
        v.transparencyDrawing = v.spuResourceList.filter((_) => _.resourceType - 0 === 3)
      }
      if (v && v.spuSaleAttr && v.spuSaleAttr.mainSaleAttr) {
        if (Array.isArray(v.spuSaleAttr.mainSaleAttr.mainSaleAttrValueList)) {
          v.spuSaleAttr.mainSaleAttr.mainSaleAttrValueList.forEach((_) => {
            if (Array.isArray(_.saleAttrImgList)) {
              _.mainGraph = _.saleAttrImgList.filter((_) => _.resourceType - 0 === 1)
              _.transparencyDrawing = _.saleAttrImgList.filter((_) => _.resourceType - 0 === 3)
            } else {
              _.mainGraph = []
              _.transparencyDrawing = []
            }
          })
        }
      }
    },
    modifyStatusChange() {
      const refs = Object.keys(this.$refs)
      refs.forEach((_) => {
        if (this.$refs[_]) this.$refs[_].isChange = false
      })
    },
    addSort(arr) {
      if (Array.isArray(arr)) {
        arr.forEach((_, index) => {
          arr[index].sort = index
        })
      }
    },
    transChanneInfo() {
      const spuData = JSON.parse(JSON.stringify(this.spuData))
      if (Array.isArray(spuData.channelInfoList)) {
        spuData.channelInfoList.forEach((_) => {
          if (_.channelId !== '06') return
          transSavaData(_.spuChannelBaseAttr)
          transSavaData(_.spuChannelCategoryAttrList, false)
          if (Array.isArray(_.spuChannelBaseAttrCopy)) {
            _.spuChannelBaseAttrCopy.forEach((copyItem, index) => {
              const item = _.spuChannelBaseAttr.find((i) => i.attrKey === copyItem.attrKey)
              if (item) _.spuChannelBaseAttrCopy[index] = item
            })
          }
          _.spuChannelBaseAttr = _.spuChannelBaseAttrCopy
          delete _.spuChannelBaseAttrCopy
          _.mainGraph = _.mainGraph || []
          _.transparencyDrawing = _.transparencyDrawing || []
          _.spuResourceList = [..._.mainGraph, ..._.transparencyDrawing]
          if (_.spuChannelDesc && _.spuChannelDesc.contentResourceList) this.addSort(_.spuChannelDesc.contentResourceList)
          this.addSort(_.spuChannelResourceList)
          this.addSort(_.spuResourceList)
          delete _.mainGraph
          delete _.transparencyDrawing
          if (_.spuSaleAttr && _.spuSaleAttr.mainSaleAttr && _.spuSaleAttr.mainSaleAttr.mainSaleAttrValueList) {
            if (!Array.isArray(_.spuSaleAttr.mainSaleAttr.mainSaleAttrValueList)) return
            _.spuSaleAttr.mainSaleAttr.mainSaleAttrValueList.forEach((_) => {
              _.mainGraph = _.mainGraph || []
              _.transparencyDrawing = _.transparencyDrawing || []
              _.saleAttrImgList = [..._.mainGraph, ..._.transparencyDrawing]
              this.addSort(_.saleAttrImgList)
              delete _.mainGraph
              delete _.transparencyDrawing
            })
          }
        })
      }
      return spuData
    },
    // 渠道信息
    async saveSpuChannelInfo() {
      try {
        this.changeLoading(true)
        const { code } = await this.saveSpuChannelInfoFun(this.transChanneInfo())
        if (code === '0') {
          this.$message({
            type: 'success',
            message: '保存成功'
          })
          if (!this.increased) {
            this.isShowButton = true
          }
          this.requestData()
        }
      } finally {
        this.changeLoading(false)
      }
    }
  }
}
</script>
<style lang="scss" scoped>
$padding: 12px;
.spu-series {
  padding: $padding;
  position: relative;
  .btn-list {
    z-index: 999;
    position: absolute;
    right: $padding;
    display: flex;
    align-items: center;
  }
}
</style>
